<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Configuration
 *
 * @author MinhNguyen
 */

class UserManagement {
    //put your code here
    public $users = array(); //array User object
    public $numOfUsers;
    
    public function __construct() {
        //alloccate your stuff
    }

    /**
     * Get all user who have name = $name from Users table
     * @param type $name
     * @return type
     */
    public static function withName($name) {
        $query = "SELECT * FROM Users WHERE name LIKE '%$name%'";
        $result = self::queryDB($query);
        return $result;
    }
    
    /**
     * Get all user who have dataregistered = $date from Users table
     * @param type $date
     * @return type
     */
    public static function withDateRegistered($date) {
        $query = "SELECT * FROM Users WHERE dateregistered='$date'";
        $result = self::queryDB($query);
        return $result;
    }
    
    /**
     * Get all user who have position = $position from Users table
     * @param type $position
     * @return type
     */
    public static function withPosition($position) {
        $query = "SELECT * FROM Users WHERE position='$position'";
        $result = self::queryDB($query);
        return $result;
    }
    
    /**
     * Query db to get instance with $query
     * @param type $query
     * @return \self|null
     */
    public function queryDB($query) {
        $instance = new self();
        $result = Database::getInstance()->query($query);
        if($result->returnCode == 200) {//OK
            if($result->dataTable->numOfRow >= 1) {
               $i = 0;
               while($i < $result->dataTable->numOfRow) {
                   $i++;
                   $instance->users[$i] = 
                        User::withEmail($result->dataTable->rows[$i]["email"]);
               }
               $instance->numOfUser = array_count_values($instance->users);
               return $instance;
            }
        }
        else {
            $controller = new ErrorController(new Error(), new ErrorView(), 
                "404", "Not found any user with provided name");
            $controller->returnError();
            return NULL;
        }
    }

    public function __get($key) {
        if($key == "numOfUsers") {
            return $this->numOfUsers;
        }
        elseif(array_key_exists($key, $this->users)) {
            return $this->users[$key];
        }
    }
    
    public function __set($key, $value) {
        if($key == "numOfUsers") {
            $this->numOfUsers = $value;
        }elseif(array_key_exists($key, $this->users)) {
            $this->users[$key] = $value;
        }
    }
}
?>
